package top.bingoz.wanandroid.data.http.intercept

import android.os.Build
import android.text.TextUtils
import top.bingoz.wanandroid.BuildConfig
import top.bingoz.wanandroid.common.Constants
import com.orhanobut.hawk.Hawk
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * @author su
 * @date 2018/7/26
 * @description
 */
class NetInterceptor() : Interceptor {

    var agent = "%s/%s (Android %s %s)"

    init {
        agent = String.format(agent, "WanAndroid", BuildConfig.VERSION_NAME, Build.MANUFACTURER, Build.VERSION.RELEASE)
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        val builder = request.newBuilder().removeHeader("User-Agent").header("User-Agent", agent)


        if (alreadyHasAuthorizationHeader(request)) {
            return chain.proceed(builder.build())
        }

        val token = Hawk.get<String>(Constants.TOKEN)

        if (token != null) {
            val newRequest = builder.header("Authorization", token).build()
            return chain.proceed(newRequest)
        }
        return chain.proceed(builder.build())
    }


    fun alreadyHasAuthorizationHeader(request: Request): Boolean {
        return !TextUtils.isEmpty(request.header("Authorization"))
    }


}